package com.bawei.yangzongcai___day2.MaiDongFangHong.day7;


import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bawei.yangzongcai___day2.R;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Route(path = "/tiao7/dongfanghong7")
public class MainDongFangHong7 extends AppCompatActivity  {
    SQLiteDatabase readableDatabase;
    private Button shujuku;
    List<JavaShipei.DataBean> dataBeans = new ArrayList<>();
    private ListView haole;
    Button  imageView;
    //适配器
    Mytufeisi foodAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_dong_fang_hong7);
        initView();
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                readableDatabase.execSQL("delete from food where tupian=?",new Object[]{dataBeans.get(0).getUrl()});
                dataBeans.remove(0);
                foodAdapter.notifyDataSetChanged();
                ToastUtils.showShort("删除了");
            }
        });
        shujuku.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance().build("/shujuku/laile").navigation();
            }
        });

        haole.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainDongFangHong7.this);
                builder.setIcon(R.mipmap.leak_canary_icon);
                builder.setTitle("我是标题");
                builder.setMessage("确定要进行删除吗？");
                builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        readableDatabase.execSQL("delete from food where tupian=?",new Object[]{dataBeans.get(position).getUrl()});
                        dataBeans.remove(position);
                        foodAdapter.notifyDataSetChanged();
                        ToastUtils.showShort("删除了");
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ToastUtils.showShort("取消了");
                    }
                });
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
            }
        });

        haole.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                ToastUtils.showShort("已缓存到数据库："+dataBeans.get(position).getDesc());

                SQLdongfanhongqi2 sqLyongyong= new SQLdongfanhongqi2(MainDongFangHong7.this,"yang.dp",null,2);
                SQLiteDatabase read= sqLyongyong.getReadableDatabase();
                read.execSQL("insert into yang values(?,?)",new Object[]{dataBeans.get(position).getDesc(),dataBeans.get(position).getUrl()});

                return true;
            }
        });


        SharedPreferences sp = getSharedPreferences("is", MODE_PRIVATE);
        boolean is = sp.getBoolean("is", false);
        if (is){
            //从数据库里获取数据
            //1.db  2.增删改查

            SQLdongfanhongqi1 sqLyongyong3 = new SQLdongfanhongqi1(MainDongFangHong7.this,"food.dp",null,1);
            readableDatabase = sqLyongyong3.getReadableDatabase();
            Cursor cursor = readableDatabase.query("food", null, null, null, null, null, null);
            while (cursor.moveToNext()){
                String id = cursor.getString(cursor.getColumnIndex("mingzi"));
                String title = cursor.getString(cursor.getColumnIndex("tupian"));

                JavaShipei.DataBean dataBeansql = new JavaShipei.DataBean();
                dataBeansql.setDesc(id);
                dataBeansql.setUrl(title);
                //添加到集合
                dataBeans.add(dataBeansql);//数据源
            }


            foodAdapter = new Mytufeisi();
            //设置适配器
            haole.setAdapter(foodAdapter);

            ToastUtils.showShort("数据库");




        }
        else
        {
            ToastUtils.showShort("网络");
            new Mydamowang().execute("https://gank.io/api/v2/data/category/Girl/type/Girl/page/1/count/30");
        }



    }

    public class Mydamowang extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... strings) {
            try {
                URL url = new URL(strings[0]);
                try {
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("GET");
                    httpURLConnection.setReadTimeout(5000);
                    httpURLConnection.setConnectTimeout(5000);
                    httpURLConnection.connect();
                    if ((httpURLConnection.getResponseCode()) == 200) {
                        InputStream inputStream = httpURLConnection.getInputStream();
                        BufferedReader inputStream1 = new BufferedReader(new InputStreamReader(inputStream));
                        String src = "";
                        StringBuffer stringBuffer = new StringBuffer();
                        while ((src = inputStream1.readLine()) != null) {
                            stringBuffer.append(src);
                        }
                        String s = stringBuffer.toString();
                        return s;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s != null) {
                Gson gson = new Gson();
                JavaShipei javaShipei = gson.fromJson(s, JavaShipei.class);
                dataBeans = javaShipei.getData();
                SharedPreferences sp = getSharedPreferences("is", MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putBoolean("is", true);
                edit.commit();

                SQLdongfanhongqi1 sqLyongyong3 = new SQLdongfanhongqi1(MainDongFangHong7.this,"food.dp",null,1);
                SQLiteDatabase readableDatabase = sqLyongyong3.getReadableDatabase();
                for (JavaShipei.DataBean dataBean : dataBeans) {
                    readableDatabase.execSQL("insert into food values (?,?)",new Object[]{dataBean.getDesc(),dataBean.getUrl()});
                }


                Mytufeisi mytufeisi = new Mytufeisi();
                haole.setAdapter(mytufeisi);
            }
        }
    }

    public class Mytufeisi extends BaseAdapter {

        @Override
        public int getCount() {
            return dataBeans.size();
        }

        @Override
        public Object getItem(int position) {
            return dataBeans.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Verhander verhander = new Verhander();
            if (convertView == null) {
                convertView = LayoutInflater.from(MainDongFangHong7.this).inflate(R.layout.maidongfanghong7, null);
                verhander.imageView = convertView.findViewById(R.id.dongfang7img);
                verhander.textView = convertView.findViewById(R.id.dongfang7text);
                convertView.setTag(verhander);
            } else {
                verhander = (Verhander) convertView.getTag();
            }
            verhander.textView.setText(dataBeans.get(position).getDesc());
            Glide.with(MainDongFangHong7.this).load(dataBeans.get(position).getUrl()).into(verhander.imageView);

            return convertView;
        }
    }

    public class Verhander {
        TextView textView;
        ImageView imageView;
    }


    private void initView() {
        shujuku = findViewById(R.id.shujuku);
        haole = findViewById(R.id.haole);
        imageView = findViewById(R.id.imageView);
    }
}
